<?php
// +-------------------------------------------------------------------
// | 
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Kcdns\Service\Wechat;

/**
 * 微信操作
 *
 * 引用 jssdk : O('wechat')->load()->jssdk();
 */
class Service
{

    protected $appKey;
    protected $appSecret;

    public function __construct()
    {
        if (WX_JS_CONFIG_OPEN_DEBUG) {
            $this->appKey = WX_JS_CONFIG_APP_KEY;
            $this->appSecret = WX_JS_CONFIG_APP_SECRET;
        } else {
            $this->getWxConfig();
        }
    }

    protected function getWxConfig($where = [])
    {
        $where OR $where = array(
            'type' => 'weixin',
            'status' => 1
        );
        $payConfig = M('OauthSettings')->where($where)->find();
        if (!$payConfig) {
            throw new \Exception('无效的微信配置');
        }
        $payConfig['config'] = json_decode(kcone_think_decrypt($payConfig['config']), true);

        $config = array();
        foreach ($payConfig['config'] as $item) {
            $config[$item['key']] = $item['val'];
        }

        $this->appKey = $config['APP_KEY'];
        $this->appSecret = $config['APP_SECRET'];
    }

    // 导入微信 JSSDK
    public function importJsSdk()
    {
        return Jssdk::getInstance()->import($this->appKey, $this->appSecret);
    }

    /**
     * 获取微信操作对象
     */
    public function load()
    {
        $config = [
            'appid' => $this->appKey,
            'appsecret' => $this->appSecret
        ];
        return Wechat::getInstance($config);
    }

    public function getSignPackage($url = '')
    {
        return Jssdk::getInstance()->getSignPackage($this->appKey, $this->appSecret, $url);
    }

    public function updateJsApiTicket()
    {
        return Jssdk::getInstance()->updateJsApiTicket($this->appKey, $this->appSecret);
    }
}